package httphandle

import (
	"emb/emb_server/util/dbutil"
	"emb/emb_server/util/handleutil"
	"fmt"
	"net/http"
)

//发送消息：
//s userID  string,friendOrGroupID string,msgContent string
//r Message string

func sendMessage(w http.ResponseWriter, r *http.Request) {

	httpCode := http.StatusOK
	info := "success"
	var information interface{}

	fmt.Println("请求方IP地址：", r.RemoteAddr)
	defer func() {
		handleutil.SendMsg(w, httpCode, info, information)
	}()

	setHeader(w)

	err := r.ParseForm()
	if err != nil {
		httpCode = http.StatusBadRequest
		info = "参数解析失败！请使用x-www-form-urlencoded格式传输参数数据！"
		httpCode = http.StatusBadRequest
		return
	}

	sender := r.Form["userID"]
	receiver := r.Form["friendOrGroupID"]
	content := r.Form["msgContent"]

	fmt.Println("sendMessage:", sender)
	fmt.Println("sendMessage:", receiver)
	fmt.Println("sendMessage:", content)

	info, ok := insertMessages(sender[0], receiver[0], content[0])
	if !ok {
		httpCode = http.StatusBadRequest

	}

}

//插入messages 表 数据
func insertMessages(sender string, receiver string, content string) (string, bool) {
	info := "success"
	sql := "insert into messages(content,sender,receiver) values ($1,$2,$3)"

	if sender == "" || receiver == "" || content == "" {
		info = "sender , receiver, content ,one of them is null"
		return info, false
	}

	dbutil.InitDb()
	db := dbutil.GetDb()
	defer dbutil.CloseDb(db)

	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		fmt.Println("From:sendMessage.Prepare")
		info = "From:sendMessage.Prepare" + err.Error()
		return info, false
	}

	_, err = stmt.Exec(content, sender, receiver)
	if err != nil {
		fmt.Println("From:sendMessage.Exec")
		info = "From:sendMessage.Exec" + err.Error()
		return info, false
	}

	// affect, err := result.RowsAffected()
	// if err != nil {
	// 	fmt.Println("From:sendMessage.RowAffected")
	// 	info = "From:sendMessage.RowAffected" + err.Error()
	// 	return info, false
	// }

	// if affect != 1 {
	// 	fmt.Println("From:sendMessage.RowAffected")
	// 	info = "send "
	// 	return info, false
	// }

	return info, true
}
